package com.linkstec.base.service;

import com.alibaba.fastjson.JSONObject;
import com.linkstec.base.constant.SysConstant;
import com.linkstec.base.util.HttpClientUtil;
import com.linkstec.base.util.PropUtil;
import com.linkstec.base.util.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class TimeScheduler {

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private PropUtil propUtil;

    //@Scheduled(cron = "0 0 0/1 * * ?")
    @Scheduled(cron = "0 */90 * * * ?")
    public void timeTask() {
        /* 定时器每一个半小时执行一次*/

        // ticket判断是否为空
        if (StringUtils.isNotBlank(redisUtil.get(SysConstant.ComponentVerifyTicket).toString())) {
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("component_appid", propUtil.wechat_app_id);
            params.put("component_appsecret", propUtil.wechat_secret);
            params.put(SysConstant.ComponentVerifyTicket, redisUtil.get(SysConstant.ComponentVerifyTicket));
            //微信接口客户端
            String object = HttpClientUtil.sendPost("https://api.weixin.qq.com/component/api_component_token",params);
            //保存获取的token 两个小时
            String token = JSONObject.parseObject(object).getString(SysConstant.ComponentAccessToken);
            redisUtil.set(SysConstant.ComponentAccessToken,token,7200l);
            getPreAuthCode(token,propUtil.wechat_app_id);
        }
    }

   public String getPreAuthCode(String accessToken,String appId ) {
       if (StringUtils.isNotBlank(accessToken)) {
           Map<String, Object> params = new HashMap<String, Object>();
           params.put("component_appid", propUtil.wechat_app_id);
           params.put(SysConstant.ComponentAccessToken, accessToken);
           //微信接口客户端
           String object = HttpClientUtil.sendPost("https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token=COMPONENT_ACCESS_TOKEN", params);
           //保存获取的code
           String code = JSONObject.parseObject(object).getString(SysConstant.pre_auth_code);
           redisUtil.set(SysConstant.pre_auth_code, code, 1800l);
           return code;
       }else {
           return null;
       }
   }

}

